package com.proxy.server;

import com.proxy.MessageTransfer;
import io.grpc.stub.ServerCalls.UnaryMethod;
import io.grpc.stub.StreamObserver;

import java.lang.reflect.Method;


public class MethodInvocation implements UnaryMethod<MessageTransfer, Object> {
    // grpc service 实例类
    private final Object serviceToInvoke;
    private final Method method;

    public MethodInvocation(Object serviceToInvoke, Method method) {
        this.serviceToInvoke = serviceToInvoke;
        this.method = method;
    }

    @Override
    public void invoke(MessageTransfer request, StreamObserver<Object> responseObserver) {
        if (method.getParameterTypes().length != request.getLength()) {
            return;
        }
        try {
            // 通过反射形式，对服务调用
            Object[] requestParams = request.retriveRequestParams();
            Object returnObj = method.invoke(serviceToInvoke, requestParams);
            responseObserver.onNext(returnObj);
        } catch (Exception ex) {
            responseObserver.onError(ex);
        } finally {
            responseObserver.onCompleted();
        }
    }


}
